import store from '@/store'
import { RoleEnum } from '@/enums/roleEnum'
import projectSetting from '@/settings/projectSetting'
import { PermissionModeEnum } from '@/settings/types'
import { isArray } from '@/utils/is'
import { intersection } from 'lodash-es'

export function usePermission() {
  // 根据value判断是否有权限
  function hasPermission(value?: RoleEnum | RoleEnum[] | string | string[], def = true): boolean {
    if (!value) {
      return def
    }

    // 获取系统的权限模式
    const permissionMode = projectSetting.permissionMode

    if (permissionMode === PermissionModeEnum.ROLE) {
      if (!isArray(value)) {
        return store.state.login.roleList?.includes(value as RoleEnum)
      }
      return (intersection(value, store.state.login.roleList) as RoleEnum[]).length > 0
    }

    if (permissionMode === PermissionModeEnum.BACK) {
      const allCodeList = store.state.permCodeList as string[]
      if (!isArray(value)) {
        return allCodeList.includes(value)
      }
      return (intersection(value, allCodeList) as string[]).length > 0
    }

    return true
  }

  return { hasPermission }
}
